package lormi.meipin.service.impl;


import lormi.meipin.common.Constants;
import lormi.meipin.common.LMQiNiuAPI;
import lormi.meipin.exception.LMException;
import lormi.meipin.service.BaseService;
import lormi.meipin.service.IQiNiuService;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 七牛接口
 * @author ThreeFeng
 * @date 2016年8月12日 下午5:46:13
 */
@Service
public class QiNiuService extends BaseService implements IQiNiuService{

	@Override
	public Map<String,String> getUpLoadToken() throws LMException{
		Map<String,String> map = new HashMap<>();
		String uptoken = LMQiNiuAPI.getToken();
		if(uptoken==null){
			throw new LMException(100018);
		}
		map.put("uptoken", uptoken);
		return map;
	}

	@Override
	public String upload(String url) throws LMException{
		if(Constants.imgIsWhite(url)){
			throw new LMException(100037);
		}
		String fileName = getFileName()+".jpg";
		if(!Base64ImgDown(url,"./"+fileName)){
			throw new LMException(100040);
		}
		LMQiNiuAPI.upload(fileName);
		File f = new File("./"+fileName);
		if(f.exists()){
			f.delete();
		}
		return fileName;
	}

	/**
	 * 获取随机文件名
	 * */
	private String getFileName(){
		return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+Math.round(Math.random()*10000);
	}
	/**
	 * 将base64的图片，写到本地
	 * */
	private boolean Base64ImgDown(String base64url,String downPath){
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			// Base64解码
			byte[] b = decoder.decodeBuffer(base64url);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
				b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(downPath);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
